package com.wx.md.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 请详述
 * @Version: 1.0
 */
@Slf4j
public class HttpUtils {
    /**
     * Description: <br>
     *
     * @param url    URL
     * @param map    body数据
     * @param header 头
     * @return 数据
     * @author lixiaofeng<br>
     * @taskId <br>
     */
    public static String doPost(String url, Map<String, Object> map, Map<String, String> header)
            throws Exception {
        CloseableHttpClient httpClient=  setHttpClienTimeOut();

        String param = "";
        // 判断map是否为空，不为空则进行遍历，封装from表单对象
        if (map != null) {
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if (entry.getValue() != null)
                    list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            // 构造from表单对象
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
            param = EntityUtils.toString(urlEncodedFormEntity);
        }

        HttpPost httpPost = new HttpPost(url + "?" + param);
        if (header != null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        // 发起请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            log.warn("response status not 200");
        }
        String result = EntityUtils.toString(response.getEntity(), "UTF-8");
        log.info("向IOT发送请求：{}？{}， response：{}", url, JSONObject.toJSONString(map), result);
        httpClient.close();
        return result;
    }
    /**
     * Description: <br>
     *
     * @param url    URL
     * @param map    body数据
     * @param header 头
     * @return 数据
     * @author lixiaofeng<br>
     * @taskId <br>
     */
    public static String doGet(String url, Map<String, Object> map, Map<String, String> header)
        throws Exception {
        CloseableHttpClient httpClient=  setHttpClienTimeOut();

        String param = "";
        // 判断map是否为空，不为空则进行遍历，封装from表单对象
        if (map != null) {
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if (entry.getValue() != null)
                    list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            // 构造from表单对象
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
            param = EntityUtils.toString(urlEncodedFormEntity);
        }

        HttpGet httpPost = new HttpGet(url + "?" + param);
        if (header != null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        // 发起请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            log.warn("response status not 200");
        }
        String result = EntityUtils.toString(response.getEntity(), "UTF-8");
        log.info("向IOT发送请求：{}？{}， response：{}", url, JSONObject.toJSONString(map), result);
        httpClient.close();
        return result;
    }
    /**
     * 超时设置
     *
     * @return </>
     */
    private static CloseableHttpClient setHttpClienTimeOut() {
        CloseableHttpClient httpClient;
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(10000)
                .setConnectTimeout(6000).setConnectionRequestTimeout(6000).build();

        httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        return httpClient;
    }

}
